package com.yh.crystal.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;

public class HttpUtils {

	private static final int timeout = 10 * 1000;
	private static final String charset = "UTF-8";

	public String httpPostWithJSON(String url, String jsonstr) throws Exception {
		HttpResponse resp = HttpUtil.createPost(url).body(jsonstr).timeout(timeout).charset(charset).execute();
		if (resp.isOk()) {
			String html = resp.body();
			return toJson(html).toString();
		}
		throw new RuntimeException("response error, code=" + resp.getStatus());
	}

	public String httpGet(String url) throws Exception {
		HttpResponse resp = HttpUtil.createGet(url).charset(charset).timeout(timeout).execute();
		if (resp.isOk()) {
			String html = resp.body();
			return toJson(html).toString();
		}
		throw new RuntimeException("response error, code=" + resp.getStatus());
	}

	private net.sf.json.JSONObject toJson(String html) {
		if (StrUtil.isBlankIfStr(html)) {
			return new net.sf.json.JSONObject();
		} else {
			return net.sf.json.JSONObject.fromObject(html);
		}
	}

}
